package com.example.zzl.view;

import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ListAdapter;

import com.example.zzl.viewmodel.BaseViewModel;

/**
 * Created by ligg on 2017/2/11.
 */

public class BaseView {

    public static void initPresenter(BaseViewModel presenter) {
        initPresenter(presenter, null);
    }


    public static void initPresenter(BaseViewModel presenter, String parameter) {
        presenter.init();
        presenter.initView();
        presenter.loadData(parameter);
    }

    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
//        int col = 4;
        int col = listView.getNumColumns();
        int verticalSpacing = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            verticalSpacing = listView.getVerticalSpacing();
        }
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
                // 获取listview的每一个item
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += (listItem.getMeasuredHeight() + verticalSpacing);
        }

        totalHeight -= verticalSpacing;
        // 获取listview的布局参数

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
//        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }
}
